package com.buka.recipe.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.buka.recipe.common.result.Result;
import com.buka.recipe.common.result.ResultGenerator;
import com.buka.recipe.system.entity.Department;
import com.buka.recipe.system.entity.Role;
import com.buka.recipe.system.entity.User;
import com.buka.recipe.system.service.DepartmentService;
import com.buka.recipe.system.service.RoleService;
import com.buka.recipe.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/user")
public class UserController {

    private final DepartmentService departmentService;
    private final UserService userService;
    private final RoleService roleService;

    @Autowired
    public UserController(DepartmentService departmentService, UserService userService, RoleService roleService) {
        this.departmentService = departmentService;
        this.userService = userService;
        this.roleService = roleService;
    }

    @GetMapping("/currentUser")
    public Result<?> currentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return ResultGenerator.genSuccessResult(principal);
    }

    @PostMapping("/add")
    public Result<?> add(@RequestBody JSONObject params) {
        Integer departmentId = params.getInteger("departmentId");
        Department department = departmentService.getDepartmentById(departmentId);
        if (department == null) {
            return ResultGenerator.genFailResult("部门不存在或没有操作权限");
        }
        String username = params.getString("username");
        if (!StringUtils.hasText(username)) {
            return ResultGenerator.genFailResult("用户名不能为空");
        }
        String password = params.getString("password");
        if (!StringUtils.hasText(password)) {
            return ResultGenerator.genFailResult("密码不能为空");
        }
        String nickname = params.getString("nickname");
        if (!StringUtils.hasLength(nickname)) {
            return ResultGenerator.genFailResult("姓名不能为空");
        }
        User user = userService.getUserByUsername(username);
        if (user != null) {
            return ResultGenerator.genFailResult("用户已存在");
        }

        user = new User();
        user.setDepartment(department);
        user.setUsername(username);
        List<Integer> roleIds = params.getList("roleIds", Integer.class);
        List<Role> roles = roleService.getRoleByIds(roleIds);
        String phone = params.getString("phone");
        String avatar = params.getString("avatar");
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        user.setNickname(nickname);
        user.setPhone(phone);
        user.setAvatar(avatar);
        user.setRoles(roles);
        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/del")
    public Result<?> del(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        User user = userService.getUserById(id);
        if (user == null) {
            return ResultGenerator.genFailResult("用户不存在");
        }
        userService.delete(user);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/list")
    public Result<?> list(@RequestParam(required = false) String username,
                          @RequestParam(required = false) String name,
                          @RequestParam(required = false) String phone,
                          @RequestParam(required = false) Boolean enabled,
                          @RequestParam(required = false, defaultValue = "0") Integer current,
                          @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Page<User> users = userService.getAll(username, name, phone, enabled, current, pageSize);
        return ResultGenerator.genSuccessResult(users);
    }

    @PostMapping("/enabled")
    public Result<?> enabled(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        User user = userService.getUserById(id);
        if (user == null) {
            return ResultGenerator.genFailResult("用户不存在");
        }
        boolean enabled = params.getBoolean("enabled");
        user.setEnabled(enabled);
        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/locked")
    public Result<?> locked(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        User user = userService.getUserById(id);
        if (user == null) {
            return ResultGenerator.genFailResult("用户不存在");
        }
        boolean locked = params.getBoolean("locked");
        user.setAccountNonLocked(locked);
        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result<?> update(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        User user = userService.getUserById(id);
        if (user == null) {
            return ResultGenerator.genFailResult("用户不存在");
        }
        String nickname = params.getString("nickname");
        if (!StringUtils.hasLength(nickname)) {
            return ResultGenerator.genFailResult("姓名不能为空");
        }
        List<Integer> roleIds = params.getList("roleIds", Integer.class);
        List<Role> roles = roleService.getRoleByIds(roleIds);
        String phone = params.getString("phone");
        String avatar = params.getString("avatar");
        user.setNickname(nickname);
        user.setPhone(phone);
        user.setAvatar(avatar);
        user.setRoles(roles);
        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/updatePassword")
    public Result<?> updatePassword(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        User user = userService.getUserById(id);
        if (user == null) {
            return ResultGenerator.genFailResult("用户不存在");
        }
        String password = params.getString("password");
        if (!StringUtils.hasLength(password)) {
            return ResultGenerator.genFailResult("密码不能为空");
        }
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }
}
